package com.csi.okr.mobile.self.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.csi.okr.common.util.BasicValueUtil;
import com.csi.okr.common.util.WxUtil;
import com.csi.okr.mobile.common.task.DataTask;
import com.csi.okr.mobile.department.service.DeptService;
import com.csi.okr.mobile.self.service.SelfService;

@Controller
@RequestMapping("/self")
public class SelfController {
	@Resource
	private SelfService selfService;
	@Resource
	private DeptService deptService;
	
	/**
	 * 微信请求入口 - 当前
	 * @return
	 */
    @RequestMapping(value = "/oauth")
    public ModelAndView oauth() {
    	//回调地址
    	String redirect_url = WxUtil.DOMAIN + "/self/callback";
    	//授权地址
    	StringBuilder url = new StringBuilder();
    	url.append("https://open.weixin.qq.com/connect/oauth2/authorize");
    	url.append("?appid="+WxUtil.CORPID);
    	url.append("&redirect_uri="+redirect_url);
    	url.append("&response_type=code");
    	url.append("&scope=snsapi_base");
    	url.append("&state=oauth");
    	url.append("#wechat_redirect");
        ModelAndView mv = new ModelAndView();
        mv.setView(new RedirectView(url.toString()));
        return mv;
    }
    
    /**
	 * 微信请求入口 - 查询
	 * @return
	 */
    @RequestMapping(value = "/query")
    public ModelAndView query() {
    	//回调地址
    	String redirect_url = WxUtil.DOMAIN + "/self/callback";
    	//授权地址
    	StringBuilder url = new StringBuilder();
    	url.append("https://open.weixin.qq.com/connect/oauth2/authorize");
    	url.append("?appid="+WxUtil.CORPID);
    	url.append("&redirect_uri="+redirect_url);
    	url.append("&response_type=code");
    	url.append("&scope=snsapi_base");
    	url.append("&state=query");
    	url.append("#wechat_redirect");
    	ModelAndView mv = new ModelAndView();
    	mv.setView(new RedirectView(url.toString()));
    	return mv;
    }
    
    /**
     * 微信回调地址 
     * @param code 微信返回参数 <br>
     * @param session
     * @return
     */
    @RequestMapping(value = "/callback")
    public ModelAndView callback(@RequestParam String code,String state,HttpSession session) {
    	
    	
    	String uid = WxUtil.getEmplCode(code);
    	
    	if(uid == null)
    		return oauth();
    	
    	if (uid.equals("index") || uid.equals("lixun") || uid.equals("E100021495")) {
    		uid = "E000100834";
		} 
    	ModelAndView mv = new ModelAndView();
    	
		mv.setViewName("self/myokr");
		
		mv.addObject("emplCode", uid);
		mv.addObject("param", state);
		session.setAttribute("tree", selfService.getOrgTree(uid));
		session.setAttribute("years", BasicValueUtil.getDate2Now());
		session.setAttribute("oColor", DataTask.OCOLOR);
		session.setAttribute("krColor", DataTask.KRCOLOR);
		session.setAttribute("oState", DataTask.O_STATE);
		session.setAttribute("oTeam", DataTask.O_TEAM);
		session.setAttribute("rState", DataTask.R_STATE);
		session.setAttribute("sState", DataTask.S_STATE);
		return mv;
    }
    
    @RequestMapping(value = "/index")
    public ModelAndView index(@RequestParam String code,String param,HttpSession session) {
    	ModelAndView mv = new ModelAndView();
    	mv.setViewName("self/myokr");
    	mv.addObject("emplCode", code);
    	mv.addObject("param", param);
    	session.setAttribute("tree", selfService.getOrgTree(code));
    	session.setAttribute("years", BasicValueUtil.getDate2Now());
    	session.setAttribute("oColor", DataTask.OCOLOR);
    	session.setAttribute("krColor", DataTask.KRCOLOR);
    	session.setAttribute("oState", DataTask.O_STATE);
    	session.setAttribute("oTeam", DataTask.O_TEAM);
    	session.setAttribute("rState", DataTask.R_STATE);
    	session.setAttribute("sState", DataTask.S_STATE);
    	return mv;
    }

	/**
	 * 组织树点击跳转方法
	 * @param orgCode
	 * @param emplCode
	 * @return
	 */
	@RequestMapping(value = "/tree", method = RequestMethod.GET)
	public ModelAndView tree(@RequestParam String orgCode,String emplCode) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("self/myokr");
		mv.addObject("emplCode", emplCode);
		mv.addObject("orgCode", orgCode);
		return mv;
	}


	/**
	 * 我的OKR查询数据
	 * 
	 * @param code 员工编号
	 * @return
	 */
	@RequestMapping(value = "/okr")
	@ResponseBody
	public Object getOkr(@RequestParam int pageIndex, int pageSize,String orgCode,
			String emplCode, String month, String year, String quarter,
			String state, String odefinition) {
		return selfService.getOkrByEmplCode(pageIndex, pageSize,orgCode, emplCode,
				month, year, quarter, state, odefinition);

	}
	
	/**
	 * 过程review
	 * 
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/review", method = RequestMethod.GET)
	public ModelAndView review(@RequestParam String uniqueCode) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);// 相当于request.setAttraite("name",""),在页面中直接使用{requestScope.name}
		mv.setViewName("review");
		return mv;
	}

	/**
	 * review列表数据
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/reviewInfo")
	@ResponseBody
	public Object reviewInfo(@RequestParam String uniqueCode) {
		return selfService.getReviewInfo(uniqueCode);
	}
	
	/**
	 * 跳转review详情
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/reviewd", method = RequestMethod.GET)
	public ModelAndView reviewd(@RequestParam String uniqueCode,String reviewUuid) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);
		mv.addObject("reviewUuid", reviewUuid);
		mv.setViewName("reviewd");
		return mv;
	}
	
	/**
	 * review详情列表数据
	 * @param uniqueCode
	 * @param reviewUuid
	 * @return
	 */
	@RequestMapping(value = "/reviewdInfo")
	@ResponseBody
	public Object getReviewReason(@RequestParam String uniqueCode,String reviewUuid) {
		return selfService.getReviewDetailInfo(uniqueCode,reviewUuid);
	}
	
	/**
	 * 跳转评分与总结页面
	 * 
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/score", method = RequestMethod.GET)
	public ModelAndView score(@RequestParam String uniqueCode) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);// 相当于request.setAttraite("name",""),在页面中直接使用{requestScope.name}
		mv.setViewName("pingfeno");
		return mv;
	}

	/**
	 * 评分与总结-获取信息
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/scoreInfo")
	@ResponseBody
	public Object scoreInfo(@RequestParam String uniqueCode) {
		return selfService.getScoreInfo(uniqueCode);
	}
	
	/**
	 * 跳转评分详情页面
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/scored", method = RequestMethod.GET)
	public ModelAndView scored(@RequestParam String uniqueCode) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);
		mv.setViewName("pingfenkr");
		return mv;
	}
	
	/**
	 * 评分详情-获取信息
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/scoredInfo")
	@ResponseBody
	public Object scoredInfo(@RequestParam String uniqueCode) {
		return selfService.getScoreDetailInfo(uniqueCode);
	}
	

	/**
	 * 跳转历史版本
	 * 
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/version", method = RequestMethod.GET)
	public ModelAndView version(@RequestParam String uniqueCode) {
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode",uniqueCode);
		mv.setViewName("version");
		
		return mv;
	}
	
	/**
	 * 历史版本信息数据
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/versionInfo")
	@ResponseBody
	public Object versionInfo(@RequestParam String uniqueCode) {
		return selfService.getVersionInfo(uniqueCode);
	}

	/**
	 * 跳转版本详情
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/versiond", method = RequestMethod.GET)
	public ModelAndView versiond(@RequestParam String versionUuid) {
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("versionUuid",versionUuid);
		mv.setViewName("versiond");
		
		return mv;
	}
	
	/**
	 * 版本详情数据
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/versiondInfo")
	@ResponseBody
	public Object versiondInfo(@RequestParam String versionUuid) {
		return selfService.getVersionDetailInfo(versionUuid);
	}

	/**
	 * 跳转关联OKR页面
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/link", method = RequestMethod.GET)
	public ModelAndView link(@RequestParam String uniqueCode) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);
		mv.setViewName("link");
		return mv;
	}

	/**
	 * 关联OKR-获取信息
	 * @param uniqueCode
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/linkOkr")
	@ResponseBody
	public Object linkOkr(@RequestParam String uniqueCode,HttpSession session) {
		return selfService.getLinkOkr(uniqueCode);
	}
	
	/**
	 * 跳转OKR详情页面
	 * @param uniqueCode
	 * @return
	 */
	@RequestMapping(value = "/krview", method = RequestMethod.GET)
	public ModelAndView krview(@RequestParam String uniqueCode) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("uniqueCode", uniqueCode);
		mv.setViewName("krview");
		return mv;
	}
	
	
	/**
	 * OKR详情 - 获取信息
	 * @param uniqueCode
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/krviewInfo")
	@ResponseBody
	public Object krviewInfo(@RequestParam String uniqueCode,HttpSession session) {
		return selfService.getkrviewInfo(uniqueCode);
	}
	
	/**
	 * 文件下载
	 * 
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/download/{uuid}")
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable String uuid) {
		
		Map<String, Object> map = selfService.getScoreReportFile(uuid);
		
		if(map == null){
			response.setCharacterEncoding("utf-8");
			response.addHeader("expires", "0");
			response.addHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=utf-8");
			try {
				response.getWriter().write("<script>alert('找不到文件!');</script>");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}

		String REPORT_FILE_NAME = map.get("REPORT_FILE_NAME").toString();
		String REPORT_FILE_SYS_PATH = map.get("REPORT_FILE_SYS_PATH").toString();
		String REPORT_FILE_SYS_NAME = map.get("REPORT_FILE_SYS_NAME").toString();
		
		String filePath = REPORT_FILE_SYS_PATH + REPORT_FILE_NAME;

		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			filePath = new String(filePath.getBytes("utf-8"), "utf-8");
			response.setContentType("application/x-msdownload");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" + REPORT_FILE_NAME);
			bis = new BufferedInputStream(new FileInputStream((filePath)));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			int i = 0;

			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
				i++;
			}
			bos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				bis = null;
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				bos = null;
			}
		}

	}
	
}
